<template>
  <div class="list-common-table">
    <t-row justify="space-between">
      <t-button v-permission="authority.SYS_ROLE_ADD" @click="add">
        <template #icon><add-icon /></template>
        新建
      </t-button>
    </t-row>

    <div class="table-container">
      <t-table
        :data="renderData"
        :columns="columns"
        row-key="id"
        :hover="true"
        :pagination="pagination"
        :loading="loading"
        :header-affixed-top="headerAffixedTop"
        table-layout="auto"
        size="small"
        @page-change="pageChange"
      >
        <template #operations="{ row }">
          <t-space>
            <t-button
              v-permission="authority.SYS_ROLE_PERM"
              variant="text"
              size="small"
              theme="primary"
              @click="perm(row.id)"
            >
              <template #icon>
                <tools-icon />
              </template>
              权限
            </t-button>
            <t-button
              v-permission="authority.SYS_ROLE_EDIT"
              variant="text"
              size="small"
              theme="primary"
              @click="edit(row)"
            >
              <template #icon>
                <edit-icon />
              </template>
              编辑
            </t-button>
            <t-popconfirm
              :content="`此操作将永久删除该用户(${row.username}), 是否继续?`"
              theme="danger"
              @confirm="del(row.id)"
            >
              <t-button v-permission="authority.SYS_ROLE_DEL" variant="text" size="small" theme="danger">
                <template #icon>
                  <delete-icon />
                </template>
                删除
              </t-button>
            </t-popconfirm>
          </t-space>
        </template>
      </t-table>
    </div>
    <role-form v-model:visible="formDialogVisible" :form-data="formData" @refresh="refresh" />
    <t-dialog :visible="permModalVisible" header="分配权限" @confirm="handleOk" @close="handleClose">
      <t-tree
        ref="treeRef"
        v-model:value="checkedKeys"
        :data="treeData"
        :checkable="true"
        :expand-level="1"
        :check-strictly="true"
        value-mode="all"
      />
    </t-dialog>
  </div>
</template>
<script setup lang="ts">
import { AddIcon, DeleteIcon, EditIcon, ToolsIcon } from 'tdesign-icons-vue-next';
import { MessagePlugin } from 'tdesign-vue-next';
import { computed, ref } from 'vue';
import { usePagination, useRequest } from 'vue-request';

import { getAllTree, menuTreeOf } from '@/api/upms/menu';
import { deleteRole, getRolePage, updatePermission } from '@/api/upms/role';
import { prefix } from '@/config/global';
import { DATA_SCOPES } from '@/constants';
import { useSettingStore } from '@/store';
import authority from '@/utils/authority';
import defaultPageOptions from '@/utils/pagination';
import { assembleTree } from '@/utils/tools';

import RoleForm from './components/role-form.vue';

const store = useSettingStore();

const formData = ref();

const columns = [
  { title: 'ID', colKey: 'id' },
  { title: '角色名称', colKey: 'roleName' },
  { title: '角色编码', colKey: 'roleCode' },
  { title: '角色描述', colKey: 'roleDesc' },
  {
    title: '数据权限',
    colKey: 'dsType',
    cell: (h: any, { row }: { row: any }) => {
      return DATA_SCOPES.find((scope) => scope.value === row.dsType)?.label;
    },
  },
  { title: '操作', colKey: 'operations' },
];

const pagination = computed(() => ({
  current: current.value,
  pageSize: pageSize.value,
  showTotal: true,
  showPageSize: true,
  total: total.value,
}));

const { data, loading, refresh, current, pageSize, total } = usePagination(getRolePage, { ...defaultPageOptions });

const renderData = computed(() => data.value?.records || []);

const pageChange = (curr: any) => {
  if (pageSize.value !== curr.pageSize) {
    pageSize.value = curr.pageSize;
  }
  if (current.value !== curr.current) {
    current.value = curr.current;
  }
};

// 弹出框标记
const formDialogVisible = ref(false);

const permModalVisible = ref(false);

const { data: treeData } = useRequest(async () => assembleTree(await getAllTree()));

const add = () => {
  formData.value = {};
  formDialogVisible.value = true;
};
const edit = (e: any) => {
  formDialogVisible.value = true;
  formData.value = { ...e };
};
const del = async (id: string) => {
  await deleteRole(id).then(() => {
    MessagePlugin.success('删除成功');
    refresh();
  });
};

const checkedKeys = ref<string[]>([]);

const treeRef = ref();

const roleId = ref<string>('');

const { runAsync } = useRequest((id) => menuTreeOf(id), {
  manual: true,
});

const perm = async (id: string) => {
  roleId.value = id;
  const menuIds = await runAsync(id);
  checkedKeys.value = menuIds;
  permModalVisible.value = true;
};

const handleOk = () => {
  if (checkedKeys.value?.length > 0) {
    updatePermission({
      roleId: roleId.value,
      menuId: checkedKeys.value.join(','),
    }).then(() => {
      MessagePlugin.success('分配成功');
      permModalVisible.value = false;
    });
  } else {
    MessagePlugin.error('请选择权限');
  }
};
const handleClose = () => {
  permModalVisible.value = false;
};

const headerAffixedTop = computed(
  () =>
    ({
      offsetTop: store.isUseTabsRouter ? 48 : 0,
      container: `.${prefix}-layout`,
    }) as any, // TO BE FIXED
);
</script>

<style lang="less" scoped>
.list-common-table {
  background-color: var(--td-bg-color-container);
  padding: var(--td-comp-paddingTB-xxl) var(--td-comp-paddingLR-xxl);
  border-radius: var(--td-radius-medium);

  .table-container {
    margin-top: var(--td-comp-margin-xxl);
  }
}

.form-item-content {
  width: 100%;
}

.operation-container {
  display: flex;
  justify-content: flex-end;
  align-items: center;

  .expand {
    .t-button__text {
      display: flex;
      align-items: center;
    }
  }
}

.payment-col {
  display: flex;

  .trend-container {
    display: flex;
    align-items: center;
    margin-left: var(--td-comp-margin-s);
  }
}
</style>
